﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Business.EntityFrameworkCore;
using mozhi.smarterp.Business.Purchases;
using mozhi.smarterp.Business.Purchases.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Business.Repositories.Purchase
{
    public class PurchaseOrderReceiptRepository : EfCoreRepository<BusinessDbContext, PurchaseOrderReceipt, Guid>, IPurchaseOrderReceiptRepository
    {
        public PurchaseOrderReceiptRepository(IDbContextProvider<BusinessDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<int> GetCountAsync(Guid? orderId, Guid? orderItemId, Guid? receiptId, Guid? receiptItemId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<PurchaseOrderReceipt>().AsNoTracking()
                .WhereIf(orderId.HasValue, x => x.OrderId == orderId)
                .WhereIf(orderItemId.HasValue, x => x.OrderItemId == orderItemId)
                .WhereIf(receiptId.HasValue, x => x.ReceiptId == receiptId)
                .WhereIf(receiptItemId.HasValue, x => x.ReceiptItemId == orderItemId)
                .CountAsync(cancellationToken);
            return count;
        }

        public async Task<List<PurchaseOrderReceipt>> GetListAsync(Guid? orderId, Guid? orderItemId, Guid? receiptId, Guid? receiptItemId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var entities = await dbContext.Set<PurchaseOrderReceipt>().AsNoTracking()
                 .WhereIf(orderId.HasValue, x => x.OrderId == orderId)
                .WhereIf(orderItemId.HasValue, x => x.OrderItemId == orderItemId)
                .WhereIf(receiptId.HasValue, x => x.ReceiptId == receiptId)
                .WhereIf(receiptItemId.HasValue, x => x.ReceiptItemId == orderItemId)
                .ToListAsync(cancellationToken);
            return entities;
        }
    }
}
